package com.xxx.lib

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import androidx.fragment.app.Fragment
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.engine.CropFileEngine
import com.xxx.lib.utils.ImageLoaderUtils
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropImageEngine

/**
 * 自定义裁剪
 */
internal class ImageCropEngine(private val aspectRatioX: Float, private val aspectRatioY: Float) :
    CropFileEngine {

    override fun onStartCrop(
        fragment: Fragment,
        srcUri: Uri,
        destinationUri: Uri,
        dataSource: ArrayList<String>,
        requestCode: Int
    ) {
        UCrop.of(srcUri, destinationUri, dataSource).apply {
            withOptions(buildOptions())
            setImageEngine(uCropImageEngine)
            start(fragment.requireActivity(), fragment, requestCode)
        }
    }

    private val uCropImageEngine = object : UCropImageEngine {
        override fun loadImage(context: Context, url: String, imageView: ImageView) {
            if (!ImageLoaderUtils.assertValidRequest(context)) return
            GlideApp.with(context).load(url).override(180, 180).into(imageView)
        }

        override fun loadImage(
            context: Context,
            url: Uri,
            maxWidth: Int,
            maxHeight: Int,
            call: UCropImageEngine.OnCallbackListener<Bitmap>?
        ) {
            GlideApp.with(context).asBitmap().load(url).override(maxWidth, maxHeight)
                .into(object : CustomTarget<Bitmap?>() {
                    override fun onResourceReady(
                        resource: Bitmap, transition: Transition<in Bitmap?>?
                    ) {
                        call?.onCall(resource)
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {
                        call?.onCall(null)
                    }
                })
        }
    }

    /**
     * 配制UCrop，可根据需求自我扩展
     */
    private fun buildOptions(): UCrop.Options {
        return UCrop.Options().apply {
            withAspectRatio(aspectRatioX, aspectRatioY)
            setCropOutputPathDir(PathConfig.DIR_CACHE_PICTURESELECTOR)
            setHideBottomControls(true)
            isDarkStatusBarBlack(true)
            setStatusBarColor(Color.WHITE)
            setToolbarColor(Color.WHITE)
        }
    }
}